﻿using System;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace Medianamik.Core.Sugar
{
    public static class Serialization
    {
        private static string UTF8ByteArrayToString(byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            string constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        private static Byte[] StringToUTF8ByteArray(string pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }

        /// <summary>
        /// Serialiser un type Generic
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SerializeObject<T>(T obj)
        {
            try
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                using (MemoryStream memoryStream = new MemoryStream())
                using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
                {
                    xs.Serialize(xmlTextWriter, obj);
                    return UTF8ByteArrayToString(memoryStream.ToArray());
                }
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Reconstruct an object from an XML string
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T DeserializeObject<T>(string xml)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml)))
            using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
            {
                return (T)xs.Deserialize(memoryStream);
            }
        }

        public static string GetJsonFromFile(string filePath)
        {
            using (var sr = new StreamReader(filePath))
                return sr.ReadToEnd();
        }
    }
}